package com.lab.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lab.pojo.Lab;
import com.lab.service.LabService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/lab")
public class LabController {
    @Resource
    LabService labService;
    Map<String,Object> result=new HashMap<>();
    @RequestMapping(value = "/listByPage",method = RequestMethod.POST)
    public Map<String,Object> listByPage(Integer page, Integer rows){
        //设置分页参数
        page=(page-1)*rows;
        PageHelper.offsetPage(page, rows);
        //查询所有数据
        List<Lab> list=labService.allLabs();

        //使用PageInfo封装查询结果
        PageInfo<Lab> pageInfo=new PageInfo<Lab>(list);
        for(Lab lab:list){
            if(lab.getState().equals("1")){
                lab.setState("正常");
            }else{
                lab.setState("停用");
            }
        }
        //从PageInfo对象取出查询结果
        //总记录数
        long total=pageInfo.getTotal();
        //当前页数据列表
        List<Lab> labsList=pageInfo.getList();
        result.put("total", total);
        result.put("rows", labsList);
        return result;
    }
    /**
     * 添加和修改
     * @param lab
     * @return
     */
    @RequestMapping(value="/saveLab",method = RequestMethod.POST)
    public Map<String,Object> saveLab(Lab lab){
        try {
            labService.saveLab(lab);
            result.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }

    /**
     * 数据回显
     * @param lab_id
     * @return
     */
    @RequestMapping(value="/findLabById",method = RequestMethod.GET)
    public Lab findLabById(Lab lab_id) {
        return labService.findLabById(lab_id);
    }

    /**
     *删除数据
     * @param lab_id
     * @return
     */
    @RequestMapping(value="/deleteLab",method = RequestMethod.DELETE)
    public Map<String,Object> deleteLab(Long[] lab_id){
        try {
            labService.deleteLab(lab_id);
            result.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }
    @RequestMapping("/findLab")
    public List findLab(){
        List<Lab> list=labService.findLab();
        List list1=new ArrayList();
        for(Lab l:list){
            list1.add(l.getLab_id());
        }
        System.out.println(list1);
        return list1;
    }
}
